
package com.jiangxiaofei.citycloud.base;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.NetworkRequest;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jiangxiaofei.citycloud.R;
import com.jiangxiaofei.citycloud.constants.Constants;
import com.jiangxiaofei.citycloud.util.ASimpleCacheUtils;
import com.jiangxiaofei.citycloud.util.ExitUtil;
import com.jiangxiaofei.citycloud.util.SharedPreferencesUtil;
import com.jiangxiaofei.citycloud.util.StringUtil;
import com.jiangxiaofei.citycloud.view.MyTextView;
import com.taobao.sophix.SophixManager;

import java.util.Map;


/**
 * @className BaseActivity
 * @描述 公共基类
 * @作者JiangXFei
 * @日期2017/7/19 11:49
 * @修改日期
 * @版本
 */
public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {
    protected String TAG, urlStr, device_token;
    //mPushAgent.disable(); 来关闭客户端的通知服务。通过mPushAgent.isEnabled()来查询状态。 状态表示有没有启用/关闭推送功能， 不表示推送后台服务的运行状态。
    public Context mContext;//上下文
    public BaseActivity mActivity;
    public Map<String, String> paramsMap;//参数map
    public LinearLayout back_layout, centertitle_layout;
    public ImageView mLeftOne, mLeftTwo, mleftThree, mRightTwo, mRightThree, mCenterone, image_view, mCentertwo, iv_record;
    public MyTextView mLeftThree, mRightOne, mCenterTitle, mtv_context, load_context, mtv_load;
    private long firstTime, spaceTime, secondTime;
    public RelativeLayout rl_layout;
    private FrameLayout rl_dialog, not_view;
    public NetworkRequest networkRequest;
    public String imageType = "phone";
    public ASimpleCacheUtils aSimpleCacheUtils;
    private Intent startIntent;
    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA
    };
    public PopupWindow mPopupWindowPublish;
    private View popupView;

    @Override
    protected void onResume() {
        super.onResume();
        SophixManager.getInstance().queryAndLoadNewPatch();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        mActivity = this;
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        TAG = getClass().getSimpleName();
        aSimpleCacheUtils = new ASimpleCacheUtils(mContext);
//         PushAgent.getInstance(mContext).onAppStart();//此方法与统计分析sdk中统计日活的方法无关！请务必调用此方法！
        ExitUtil.getInstance().addActivity(this);
        //屏幕像素
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        Constants.width = dm.widthPixels; // 当前屏幕像素
        Constants.height = dm.heightPixels; // 当前屏幕像素
        //userid
        Constants.user_id = SharedPreferencesUtil.getPrefString(mContext,
                "userId", "");
        Constants.user_Name = SharedPreferencesUtil.getPrefString(mContext,
                "userName", "0");
        initView(savedInstanceState);
        processLogic(savedInstanceState);
        setListener();
    }

    /**
     * 查找View
     *
     * @param id   控件的id
     * @param <VT> View类型
     * @return
     */
    protected <VT extends View> VT getViewById(@IdRes int id) {
        return (VT) findViewById(id);
    }

    /**
     * 初始化布局
     */
    protected abstract void initView(Bundle savedInstanceState);

    /**
     * 给View控件添加事件监听器
     */
    protected abstract void setListener();

    /**
     * 初始化view控件 处理业务逻辑，状态恢复等操作
     *
     * @param savedInstanceState
     */
    protected abstract void processLogic(Bundle savedInstanceState);


//    public boolean dispatchTouchEvent(MotionEvent ev) {
//
//        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//            if (new TimingExitService() != null) {
//                if(startIntent!=null){
//                    startIntent =  new Intent(this, TimingExitService.class);
//                    stopService(startIntent);
//                }else{
//                    startIntent =  new Intent(this, TimingExitService.class);
//                    startService(startIntent);
//                }
//
//
//            }
//        }
//        return super.dispatchTouchEvent(ev);
//
//    }

    /**
     * 双击退出
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        String currentActivityName = this.getClass().getSimpleName();
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0
                && currentActivityName.equals("HomeActivity")) {
            firstTime = System.currentTimeMillis();
            spaceTime = firstTime - secondTime;
            secondTime = firstTime;
            if (spaceTime > 2000) {
                Toast.makeText(mContext, "点击第二次退出", Toast.LENGTH_SHORT).show();
                return false;
            } else {
//                Intent i = new Intent(Intent.ACTION_MAIN);
//                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                i.addCategory(Intent.CATEGORY_HOME);
//                startActivity(i);
                ExitUtil.getInstance().exit();
            }
        }

//        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
//            finish();
//        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 初始化标题栏
     *
     * @Description:
     * @ClassName:BaseActivity
     * @date 2016-7-29 11:18
     * @author lml
     */
    public void initTitle() {
        back_layout = (LinearLayout) findViewById(R.id.ll_return);
        centertitle_layout = (LinearLayout) findViewById(R.id.ll_centertitle);
        rl_layout = (RelativeLayout) findViewById(R.id.rl_title);
        mCenterTitle = (MyTextView) findViewById(R.id.tv_centertitle);
        mLeftOne = (ImageView) findViewById(R.id.iv_leftone);
        mLeftTwo = (ImageView) findViewById(R.id.iv_lefttwo);
        mleftThree = (ImageView) findViewById(R.id.iv_leftthree);
        mLeftThree = (MyTextView) findViewById(R.id.tv_leftthree);
        mRightOne = (MyTextView) findViewById(R.id.tv_rightone);
        mRightTwo = (ImageView) findViewById(R.id.iv_righttwo);
        mRightThree = (ImageView) findViewById(R.id.iv_rightthree);
        mCenterone = (ImageView) findViewById(R.id.iv_centerone);
        mCentertwo = (ImageView) findViewById(R.id.iv_centertwo);


    }


    public void hideBgTitle() {

        if (rl_layout != null) {
            rl_layout.setVisibility(View.GONE);
        }

    }

    public void showBgTitle() {

        if (rl_layout != null) {
            rl_layout.setVisibility(View.VISIBLE);
        }

    }

    public void setCTitle(String title) {
        if (StringUtil.isNotNull(title)) {
            mCenterTitle.setText(title);
            mCenterTitle.setVisibility(View.VISIBLE);
            mCenterone.setVisibility(View.GONE);
            mCentertwo.setVisibility(View.GONE);
        }

    }

    /**
     * 初始化正在加载页
     *
     * @Description:
     * @ClassName:BaseActivity
     * @date 2016-7-5 14:29
     * @author lml
     */
    public void initLoadView() {
        try {
            rl_dialog = (FrameLayout) findViewById(R.id.rl_dialog);
            image_view = (ImageView) findViewById(R.id.loadingImageView);
            load_context = (MyTextView) findViewById(R.id.id_tv_loadingmsg);
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "加载布局失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 显示正在加载页
     *
     * @Description:
     * @ClassName:BaseActivity
     * @date 2016-7-29 11:16
     * @author lml
     */
    public void showLoadView() {
        if (rl_dialog != null) {
            rl_dialog.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 隐藏正在加载页
     *
     * @Description:
     * @ClassName:BaseActivity
     * @date 2016-7-29 11:16
     * @author lml
     */
    public void hideLoadView() {
        if (rl_dialog != null) {
            rl_dialog.setVisibility(View.GONE);
        }

    }

    /**
     * 初始化没有内容页
     *
     * @Description:
     * @ClassName:BaseActivity
     * @date 2016-7-5 14:28
     * @author lml
     */
    public void initNotView() {
        not_view = (FrameLayout) findViewById(R.id.ll_not_view);
        mtv_context = (MyTextView) findViewById(R.id.mtv_context);
        mtv_load = (MyTextView) findViewById(R.id.mtv_load);
        iv_record = (ImageView) findViewById(R.id.iv_record);


    }

    /**
     * 显示没有内容页
     *
     * @Description:
     * @ClassName:BaseActivity
     * @date 2016-7-5 14:28
     * @author lml
     */
    public void showNotContext(String str) {
        not_view.setVisibility(View.VISIBLE);
        mtv_context.setText(str);
    }

    /**
     * 隐藏没有内容页
     *
     * @Description:
     * @ClassName:BaseActivity
     * @date 2016-7-5 14:28
     * @author lml
     */
    public void hideNotContext() {
        not_view.setVisibility(View.GONE);
        mtv_context.setText("暂无内容");
    }

    public void setUrlStr(String title) {
        urlStr = title;

    }

    /**
     * 左边箭头
     *
     * @Description:
     * @ClassName:BaseActivity
     * @date 2016-7-5 15:02
     * @author lml
     */
    public void setLeftOneBg(int resId) {
        if (resId == 0) {
            mLeftOne.setVisibility(View.GONE);
        } else {
            mLeftOne.setVisibility(View.VISIBLE);
        }
        mLeftOne.setImageResource(resId);
        mLeftOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mActivity.finish();
            }
        });
    }

    /**
     * 左边图片
     *
     * @Description:
     * @ClassName:BaseActivity
     * @date 2016-7-5 15:02
     * @author lml
     */
    public void setLeftTwoBg(int resId) {
        if (resId == 0) {
            mLeftTwo.setVisibility(View.GONE);
        } else {
            mLeftTwo.setVisibility(View.VISIBLE);
        }
        mLeftTwo.setImageResource(resId);
        mLeftTwo.setOnClickListener(this);
    }

    /**
     * 左边图片
     *
     * @Description:
     * @ClassName:BaseActivity
     * @date 2016-7-5 15:02
     * @author lml
     */
    public void setLeftThreeBg(int resId) {
        if (resId == 0) {
            mleftThree.setVisibility(View.GONE);
        } else {
            mleftThree.setVisibility(View.VISIBLE);
        }
        mleftThree.setImageResource(resId);
        mleftThree.setOnClickListener(this);
    }

    public void setCenteroneBg(int resId) {
        if (resId == 0) {
            mCenterone.setVisibility(View.GONE);
        } else {
            mCenterone.setVisibility(View.VISIBLE);
        }
        mCenterone.setImageResource(resId);
        centertitle_layout.setOnClickListener(this);
    }

    public void setCentertwoBg(int resId) {

        mCenterTitle.setVisibility(View.GONE);
        if (resId == 0) {
            mCentertwo.setVisibility(View.GONE);
        } else {
            mCentertwo.setVisibility(View.VISIBLE);
        }

        mCentertwo.setImageResource(resId);
        mCentertwo.setOnClickListener(this);
    }

    public void setLeftThreeText(String content) {
        if (StringUtil.isNotNull(content)) {
            mLeftThree.setVisibility(View.VISIBLE);
            mLeftThree.setText(content);
            mLeftThree.setOnClickListener(this);
        }

    }

    public void setRightOneText(String content) {
        if (StringUtil.isNotNull(content)) {
            mRightOne.setVisibility(View.VISIBLE);
            mRightOne.setText(content);
            mRightOne.setOnClickListener(this);
        }

    }

    public void setRightTwoBg(int resId) {
        if (resId == 0) {
            mRightTwo.setVisibility(View.GONE);
        } else {
            mRightTwo.setVisibility(View.VISIBLE);
        }
        mRightTwo.setImageResource(resId);
        mRightTwo.setOnClickListener(this);
    }

    public void setRightThreeBg(int resId, String type) {
        imageType = type;
        if (resId == 0) {
            mRightThree.setVisibility(View.GONE);
        } else {
            mRightThree.setVisibility(View.VISIBLE);
        }
        mRightThree.setImageResource(resId);
        mRightThree.setOnClickListener(this);
    }


    public void setRightThreeBg(int resId) {
        if (resId == 0) {
            mRightThree.setVisibility(View.GONE);
        } else {
            mRightThree.setVisibility(View.VISIBLE);
        }
        mRightThree.setImageResource(resId);
        mRightThree.setOnClickListener(this);
    }

    /**
     * 标题栏右边第三个
     *
     * @Description:
     * @ClassName:BaseActivity
     * @date 2016-7-5 14:31
     * @author lml
     */
    public void setRightThreeBgVisible(int resId) {

        if (resId != 0) {
            mRightThree.setVisibility(View.VISIBLE);
        } else {
            mRightThree.setVisibility(View.GONE);
        }

    }

    // 不随系统大小而改变
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    public static DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                return true;
            } else {
                return false;
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (startIntent != null) {
            stopService(startIntent);
        }
        ExitUtil.getInstance().removeActivity(this);
    }


    /**
     * 初始化发布popupWindow
     */
    public void initDetailPopup(View.OnClickListener listener1,
                                 View.OnClickListener listener2, View.OnClickListener cannelListener) {
        mPopupWindowPublish = new PopupWindow(mContext);
        popupView = LayoutInflater.from(mContext).inflate(R.layout.popup_ios_buttom, null);
        showAnimation(popupView);
        mPopupWindowPublish.setContentView(popupView);
        mPopupWindowPublish.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mPopupWindowPublish.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindowPublish.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPopupWindowPublish.setFocusable(true);
        mPopupWindowPublish.setOutsideTouchable(false);
        TextView tvGong = popupView.findViewById(R.id.tv_publish_gong);
        tvGong.setText("电话联系");
        TextView tcXu = popupView.findViewById(R.id.tv_publish_xu);
        tcXu.setText("短信联系");
        TextView tvCannel = popupView.findViewById(R.id.tv_cannel);
        tvGong.setOnClickListener(listener1);
        tvCannel.setOnClickListener(cannelListener);
        tcXu.setOnClickListener(listener2);
    }

    public void showDetailPopup() {
        showAnimation(popupView);
        mPopupWindowPublish.showAtLocation(getCurrentFocus(), Gravity.BOTTOM, 0, 0); // 设置背景颜色变暗
        WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
        lp.alpha = 0.7f;
        mActivity.getWindow().setAttributes(lp);
        mPopupWindowPublish.setOnDismissListener(() -> {
            WindowManager.LayoutParams lp1 = mActivity.getWindow().getAttributes();
            lp1.alpha = 1f;
            mActivity.getWindow().setAttributes(lp1);
        });
    }

    private void showAnimation(View popView) {
        AnimationSet animationSet = new AnimationSet(false);
        AlphaAnimation alphaAnimation = new AlphaAnimation(0f, 1.0f);
        alphaAnimation.setDuration(300);
        TranslateAnimation translateAnimation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 0f
        );
        translateAnimation.setDuration(300);
        animationSet.addAnimation(alphaAnimation);
        animationSet.addAnimation(translateAnimation);
        popView.startAnimation(animationSet);
    }

}
